#!/usr/bin/php
<?php
include('/root/tv_record/xmltv/settings.php.inc');
include('/root/tv_record/xmltv/sql.php.inc');


//do some removes
$sql = "DELETE FROM channels";
$result = mysql_query($sql,$connect);
$sql = "ALTER TABLE channels AUTO_INCREMENT=1";
$result = mysql_query($sql,$connect);

$sql = "DELETE FROM display_names";
$result = mysql_query($sql,$connect);
$sql = "ALTER TABLE display_names AUTO_INCREMENT=1";
$result = mysql_query($sql,$connect);

$sql = "DELETE FROM listings";
$result = mysql_query($sql,$connect);
$sql = "ALTER TABLE listings AUTO_INCREMENT=1";
$result = mysql_query($sql,$connect);

#$sql = "delete from torecord where start < now()";
#$result = mysql_query($sql,$connect);

$xml = simplexml_load_file('/root/tv_record/xmltv/na.xml');
foreach($xml->channel as $channel) {
	$id ="";
	$insert_id = "";
	foreach($channel->attributes() as $a => $b) {
		//echo "$a = $b\n";
		$id = $b;
		$sql = "INSERT into channels (channel_id) values (\"$id\")";
		$result = mysql_query($sql,$connect) or die (mysql_error());
		$insert_id = mysql_insert_id($connect);
	}
	$c = 0;
	foreach($channel->{'display-name'} as $a => $b) {
		$sql = "INSERT into display_names (channel,display_name,display_order) values (\"$insert_id\",\"$b\",\"$c\")";
		$result = mysql_query($sql,$connect) or die (mysql_error());
		$c++;
	}
}
foreach($xml->{'programme'} as $program) {
	$start ="";
	$stop = "";
	$channel = "";
	$title = "";
	$subtitle = "";
	$date = "";
	$length = "";
	$previously_shown = "";
	$episode_num_onscreen = "";
	$episode_num_dd_progid = "";
	$desc = "";
	foreach($program->attributes() as $a => $b) {
		//echo "$a = $b\n";
		if ($a == "start") {
			$start = $b;
		}
		if ($a == "stop") {
			$stop = $b;
		}
		if ($a == "channel") {
			$channel = $b;
		}
	}
	if (isset($program->{'title'})) {
		$title = $program->{'title'};
	}
	if (isset($program->{'desc'})) {
		$desc = $program->{'desc'};
	}
	if (isset($program->{'sub-title'})) {
		$subtitle = $program->{'sub-title'};
	}
	if (isset($program->{'date'})) {
		$date = $program->{'date'};
	}
	if (isset($program->{'length'})) {
		$length = $program->{'length'};
	}
	foreach($program->{'episode-num'} as $a => $b) {
		if (!strstr($b,".")) {
			$episode_num_onscreen = $b;
		} else {
			$episode_num_dd_progid = $b;
		}
	}
	if (isset($program->{'previously-shown'})) {
		foreach($program->{'previously-shown'}->attributes() as $a => $b) {
			if ($a == "start") {
				$previously_shown = $b;
			}
		}
	}
	$desc = addslashes($desc);
	$subtitle = addslashes($subtitle);
	$title = addslashes($title);
	$sql = "insert into listings (start,end,channel,title,description,date_d,length,episode_num_dd_progid,episode_num_onscreen,previously_shown,sub_title) values ('$start','$stop','$channel','$title','$desc','$date','$length','$episode_num_dd_progid','$episode_num_onscreen','$previously_shown','$subtitle')";
	$result = mysql_query($sql,$connect) or die (mysql_error());
}
?>
